// const mysql = require("mysql2/promise");
const operations = require("./db-operations");
const crypto = require("crypto");
const pool = new operations();

// 保存聊天记录消息
const insertMessage = (params) => {
  const query = `
    INSERT INTO chat_message 
    (id, message, on_user_id, send_user_id,send_nick_name,on_nick_name, create_time) 
    VALUES (?, ?, ?, ?,?,?, ?)
  `;
  const values = [
    crypto.randomUUID(),
    params.message,
    params.receiver,
    params.send,
    params.nickName,
    params.onNickName,
    new Date()
  ];
  console.log("fskldjf",values)
  try {
    console.log("Executing SQL:", query, "with values:", values);
    // return pool.insert(query, row);
    return pool.query(query, values);
  } catch (error) {
    console.log("error", error);
  }
};

// 查询所有用户（排除密码字段）
const getAllUsers = async (userId) => {
  const query = `SELECT user_id, user_name, nick_name, create_time FROM sys_user WHERE user_id != ?`;
  try {
    console.log("Executing SQL:", query);
    const rows = await pool.query(query, [userId]);
    console.log("Query result:", rows);
    return rows;
  } catch (error) {
    console.error("Error executing query:", error);
    throw error;
  }
};

// 根据用户名查询用户
const getUserByUsername = async (username) => {
  const query = `SELECT user_id, user_name, nick_name FROM sys_user WHERE user_name = ?`;
  try {
    console.log("Executing SQL:", query);
    const rows = await pool.query(query, [username]);
    console.log("Query result:", rows);
    return rows;
  } catch (error) {
    console.error("Error executing query:", error);
    throw error;
  }
};

// 创建新用户
const createUser = async (userData) => {
  const query = `
    INSERT INTO sys_user 
    (user_id, user_name, nick_name, password, create_time) 
    VALUES (?, ?, ?, ?, ?)
  `;
  const values = [
    userData.userId,
    userData.username,
    userData.nickName,
    userData.password,
    new Date()
  ];
  try {
    console.log("Executing SQL:", query, "with values:", values);
    const result = await pool.query(query, values);
    console.log("User created:", result);
    return result;
  } catch (error) {
    console.error("Error creating user:", error);
    throw error;
  }
};

// 查询聊天记录总数
const getMessageCount = async (params) => {
  const { userId, onUserId } = params;
  
  // 参数验证
  if (!userId || !onUserId) {
    throw new Error("userId 和 onUserId 是必需的参数");
  }
  
  const query = `
    SELECT COUNT(*) as count FROM chat_message
    WHERE (send_user_id = ? AND on_user_id = ?) OR (on_user_id = ? AND send_user_id = ?)
  `;
  
  try {
    console.log("getMessageCount SQL:", query);
    console.log("getMessageCount values:", [userId, onUserId, userId, onUserId]);
    const rows = await pool.query(query, [userId, onUserId, userId, onUserId]);
    console.log("getMessageCount result:", rows);
    return rows[0].count;
  } catch (error) {
    console.error("Error executing query:", error);
    throw error;
  }
};

// 查询所有用户 (分页)
const getAllMessages = async (params) => {
  const { userId, onUserId, page = 1, limit = 100 } = params;
  
  // 参数验证
  if (!userId || !onUserId) {
    throw new Error("userId 和 onUserId 是必需的参数");
  }
  
  // 确保 page 和 limit 是有效数字
  const pageNum = parseInt(page) || 1;
  const limitNum = parseInt(limit) || 100;
  const offset = (pageNum - 1) * limitNum;
  
  // 添加调试信息
  console.log("getAllMessages params:", { userId, onUserId, page, limit });
  console.log("Calculated values:", { pageNum, limitNum, offset });
  
  // 检查参数是否有效
  if (isNaN(pageNum) || isNaN(limitNum) || isNaN(offset)) {
    throw new Error("分页参数无效");
  }
  
  // 使用字符串拼接的方式来构建LIMIT/OFFSET部分
  const query = `
    SELECT * FROM chat_message
    WHERE (send_user_id = ? AND on_user_id = ?) OR (on_user_id = ? AND send_user_id = ?)
    ORDER BY create_time DESC
    LIMIT ${offset}, ${limitNum}`;
  try {
    console.log("Executing SQL:", query);
    console.log("With values:", [userId, onUserId, userId, onUserId]);
    const rows = await pool.query(query, [userId, onUserId, userId, onUserId]);
    console.log("Query result:", rows);
    return rows;
  } catch (error) {
    console.error("Error executing query:", error);
    throw error;
  }
};

// 根据用户ID查询用户信息（返回所有字段）
const getUserById = async (userId) => {
  const query = `SELECT * FROM sys_user WHERE user_id = ?`;
  try {
    console.log("Executing SQL:", query);
    const rows = await pool.query(query, [userId]);
    console.log("Query result:", rows);
    return rows;
  } catch (error) {
    console.error("Error executing query:", error);
    throw error;
  }
};

// 更新用户信息（昵称和密码）
const updateUserInfo = async (userId, updateData) => {
  const { nickName, password } = updateData;
  
  // 动态构建更新语句
  let query = 'UPDATE sys_user SET ';
  const values = [];
  const updates = [];
  
  if (nickName !== undefined) {
    updates.push('nick_name = ?');
    values.push(nickName);
  }
  
  if (password !== undefined) {
    updates.push('password = ?');
    values.push(password);
  }
  
  if (updates.length === 0) {
    throw new Error('没有需要更新的字段');
  }
  
  query += updates.join(', ');
  query += ' WHERE user_id = ?';
  values.push(userId);
  
  try {
    console.log("Executing SQL:", query, "with values:", values);
    const result = await pool.query(query, values);
    console.log("User updated:", result);
    return result;
  } catch (error) {
    console.error("Error updating user:", error);
    throw error;
  }
};

module.exports = {
  insertMessage,
  getAllUsers, // 新增导出方法
  getAllMessages,
  getMessageCount,
  getUserByUsername, // 用户注册相关
  createUser, // 用户注册相关
  getUserById, // 个人信息相关
  updateUserInfo // 个人信息相关
};
